package com.winai.launcher.service.heartBeat;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.ks.projectbasictools.retrofit.HttpResponseListener;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.requestBean.DevicePushVersionBean;
import com.winai.launcher.bean.responseEntity.DevicePushVersionEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.DirectoryConstant;
import com.winai.launcher.constant.HttpUrls;
import com.winai.launcher.manager.UpgradeProgressManager;
import com.winai.launcher.manager.UpgradeWindowManager;
import com.winai.launcher.manager.VideoManager;
import com.winai.launcher.manager.VolumeWindow;
import com.winai.launcher.manager.WeatherManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.FileUtils;
import com.winai.launcher.utils.MD5Utils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.ServerUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * 作者：康少
 * 时间：2020/4/7 0007
 * 说明：心跳服务，用于检查版本更新
 */
public class HeartBeatService extends AbsHeartBeatService {
    private Context mContext = HeartBeatService.this;
    private static final String TAG = "---> HeartBeatService";
    private int count = 5;
    public static String md5 = "";

    private static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
    private Runnable mainThreadRunnable = () -> {
        LogUtils.d("定时心跳执行");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!NetworkUtils.hasNetwork(mContext) && count > 0) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    LogUtils.d("等待网络连接……count = " + count);
                    count--;
                }
                /**定时检查版本更新*/
                checkVersion();
                /**定时更新天气信息*/
                WeatherManager.getInstance(mContext).requestWeatherData();/*获取墨迹天气*/
            }
        }).start();
    };

    private void checkVersion() {
        DB_Common dbCommon = new DB_Common(this);
        String isFirst = dbCommon.get("isFirstOpenApp");
        if (TextUtils.isEmpty(isFirst)) {
            return;
        }
        DevicePushVersionBean mDevicePushVersionBean = new DevicePushVersionBean();
//        mDevicePushVersionBean.setName("X106F-DEV-B1.0.8-Provision-20201207-13:04");
        mDevicePushVersionBean.setName(BaseUtils.getSystemVersion());
        mDevicePushVersionBean.setEquipmentId(BaseUtils.getDeviceId());
        ServerUtils.requestJsonPost(HttpUrls.CHECK_VERSION, null, mDevicePushVersionBean
                , new HttpResponseListener<DevicePushVersionEntity>() {
                    @Override
                    public void onResponse(DevicePushVersionEntity var1, boolean isCache) {
                        if (isCache) {
                            return;
                        }
                        if (var1.getData() != null) {
                            //有更新
                            LogUtils.i("发现ROM新版本");
                            Constant.upgrading = true;
                            boolean mandatory = var1.getData().isMandatory();//true：强制更新；false：非强制更新
                            md5 = var1.getData().getMd5();
                            UpgradeProgressManager.getInstance(mContext).setVersionName(var1.getData().getVersionName());
                            UpgradeWindowManager.getInstance(mContext, var1.getData().getPath()).showTip();
                        } else {
                            LogUtils.i("无ROM更新");
                        }
                    }
                });
    }

    private void downloadFile(String path) {
        /**文件数量大于两个时，删除文件夹下所有内容*/
        List<File> fileList = FileUtils.getFile(new File(DirectoryConstant.ROM_PATH));
        if (fileList != null && fileList.size() > 2) {
            FileUtils.deleteFiles(DirectoryConstant.ROM_PATH);
        }
        long taskId = Aria.download(this)
                .load(path)     //读取下载地址
                .setFilePath(FileUtils.getLocalPath(path)) //设置文件保存的完整路径
                .ignoreFilePathOccupy()
                .create();   //创建并启动下载
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        int p = task.getPercent();    //任务进度百分比
        LogUtils.e("下载了：" + p + "%");
        String filePath = task.getFilePath();
        if (filePath.contains(DirectoryConstant.QUYI_IMG_CACHE)) {
            // doNothing
        } else {
            //版本更新下载界面更新进度
            UpgradeProgressManager.getInstance(mContext).showTip();
            UpgradeProgressManager.getInstance(mContext).setProgress(p);
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        LogUtils.e("下载完成了");
        String filePath = task.getFilePath();
        if (filePath.contains(DirectoryConstant.QUYI_IMG_CACHE)) {
            //曲艺图片缓存完成
            VideoManager.getInstance(mContext).sendNotify(filePath);
            new RemoveSpaceThread().start();//清除多余空间
        } else {
            //版本更新完成
            FileUtils.renameDownloadPath(filePath);
            UpgradeProgressManager.getInstance(mContext).setFilePath(filePath);
            UpgradeProgressManager.getInstance(mContext).setProgress(100);
        }
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task) {
        LogUtils.e("下载失败了");
        String filePath = task.getFilePath();
        if (filePath.contains(DirectoryConstant.QUYI_IMG_CACHE)) {
            //曲艺图片缓存失败
            VideoManager.getInstance(mContext).sendNotify(filePath);
//            new RemoveSpaceThread().start();//清除多余空间
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onStartService() {
        Log.d(TAG, "onStartService()");
        initListener();
        Aria.download(this).register();//注册下载
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.DOWNLOAD_ROM_COMPLETE:
                        //ROM下载完毕
                        String path = (String) argObj;
                        new Thread(() -> {
                            try {
                                moveFile(FileUtils.getLocalPath(path), "/cache/update.zip");
                                LogUtils.i("开始读取ROM文件MD5…");
                                File updateZipFile = new File("/cache/update.zip");
                                String fileMD5 = MD5Utils.getFileMD5(updateZipFile);
                                LogUtils.i("下载后的文件MD5——>" + fileMD5);
                                LogUtils.i("Http接口上的MD5——>" + md5);
                                if (md5.equals(fileMD5)) {
                                    // 执行更新操作
                                    LogUtils.i("执行更新操作");
                                    NotifyReceiverUtils.notifySystemUpgrade(mContext.getApplicationContext(), FileUtils.getLocalPath(path));
                                } else {
                                    LogUtils.e("更新文件已损坏，请联系客服");
                                    // 删除update.zip和rom下面的文件
                                    FileUtils.deleteFiles("/cache/update.zip");
                                    FileUtils.deleteFiles(DirectoryConstant.ROM_PATH);
                                    //给予用户提示
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            UpgradeProgressManager.getInstance(mContext).dismissTip();
                                            ToastKs.show(mContext, "更新文件已损坏!请重启设备检查更新");
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                LogUtils.e("更新文件已损坏，请联系客服 -1");
                            }
                        }).start();
                        break;
                }
            }
        });
    }

    @Override
    public void onStopService() {
        Log.e(TAG, "onStopService()");
        VolumeWindow.getInstance(mContext).destroy();
    }

    @Override
    public long getDelayExecutedMillis() {
        /**延迟十秒开启心跳*/
        return 10 * 1000;
    }

    @Override
    public long getHeartBeatMillis() {
        /**心跳循环周期*/
        return 60 * 60 * 1000;
    }

    @Override
    public void onHeartBeat() {
        Log.d(TAG, "onHeartBeat()");
        mainThreadHandler.post(mainThreadRunnable);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private boolean moveFile(String source, String target) {
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(target);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            Log.d(TAG, " moveFile error");
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                in.close();
                outStream.close();
                out.close();
                Log.d(TAG, " moveFile ok ");
            } catch (Exception e) {
                Log.d(TAG, " moveFile close error");
            }
        }

        return true;
    }


    private static class RemoveSpaceThread extends Thread {
        @Override
        public void run() {
            //清除曲艺图片缓存的就图片，腾出空间
            FileUtils.removeSpaceCache(DirectoryConstant.QUYI_IMG_CACHE);
        }
    }
}
